<?php
/**
 * Created by PhpStorm.
 * User: zhan
 * Date: 2017/11/9  19:27
 */
namespace app\api\logic;
use app\api\BaseModel;
use think\Cache;

class Goods extends  BaseModel{

    /**
     * 轮播图
     */
    public function banner(){
        $type=isset($this->requestData['type'])?$this->requestData['type']:'0';
        $where['status'] = 1;
        $where['type'] = $type;
        $list=db("banner")->where($where)->order("sort desc,id asc")->select();
        foreach($list as &$v){
            $v['pic']=IMG_PATH.$v['pic'];
        }
        return $list;
    }
    /**
     * 分类列表
     */
    public function category(){
        $list=db("goods_category")->where("status=1")->order("sort desc,id asc")->select();
        return $list;
    }

    /**
     * 厨房
     */
    public function kitchen()
    {
        $goods = db('goods');
        $goods_option_value=db('goods_option_value');
        $where_string = 'top_image != "" and status = 1';
        
        if (isset($this->requestData['cid'])) {
            $where['cid'] = $this->requestData['cid'];
            $where_string .= ' and cid = '.$this->requestData['cid'].'';
            $category = db("goods_category")->where(array('id'=>$this->requestData['cid']))->find();
        } else {
            $category = db("goods_category")->order("sort desc")->find();
        }
        

        $goods_top = $goods->where($where_string)->order('sort desc')->field("id,name,top_image,des")->find();

        if(!empty($goods_top)){
            $goods_top['top_image']=IMG_PATH.$goods_top['top_image'];
            $goods_top['price']=(float)($goods_option_value->where("goodsid=".$goods_top['id'])->min("price"));
        }
        
        $p=isset($this->requestData['page'])?$this->requestData['page']:'0';
        $size=isset($this->requestData['limit'])?$this->requestData['limit']:'10';


        $where['status']=1;
        $list=$goods->where($where)
            ->field("id,name,image,des")
            ->order("id desc,sort desc")->page($p,$size)->select();

        foreach($list as &$v){
            $v['image']=IMG_PATH.$v['image'];
            $v['price']= (float)($goods_option_value->where("goodsid=".$v['id'])->min("price"));
        }

        $count = $goods->where($where)
            ->field("id,name,image,des")
            ->order("id desc,sort desc")->count();
        return array("goods_top"=>$goods_top,'list'=>$list,'count'=>$count,'page_num'=>$p,'page_limit'=>$size);
    }
    /**
     * 商品列表
     */
    public function index()
    {
        $p=isset($this->requestData['page'])?$this->requestData['page']:'1';
        $size=isset($this->requestData['limit'])?$this->requestData['limit']:'10';
        $sort=isset($this->requestData['sort'])?$this->requestData['sort']:'0';
        $goods_name=isset($this->requestData['keyword'])?$this->requestData['keyword']:'';

        switch($sort){
            case 0:$order='id desc';break;
            case 1:$order='sales_num desc';break;
            case 2:$order='price asc';break;
            case 3:$order='price desc';break;
        }
        $goods = db('goods');
        $goods_option_value=db('goods_option_value');
        if (isset($this->requestData['cid'])) {//分类
            $where['cid'] = $this->requestData['cid'];
        }
        $where['g.status']=1;
        $where['g.name'] = array('like',"%$goods_name%");
        
        $list=$goods->alias("g")
            ->field("g.id,g.name,g.image,g.sales_num,g.des,min(p.price) as price,min(p.oldprice) as oldprice")
            ->join("goods_option_value p","p.goodsid=g.id")
            ->where($where)
            ->group("g.id")
            ->order($order)->page($p,$size)->select();
        foreach($list as &$v){
            $v['image']=IMG_PATH.$v['image'];
        }
        $data['data']=$list;
        $data['count']=$goods->alias("g")->where($where)->count();
        $data['page_num']=$p;
        $data['page_limit']=$size;
        return $data;
    }

    /**
     * 搜索商品
     */
    public function search_goods(){
        if(!isset($this->requestData['keyword']))return array('message'=>'缺少搜索商品名称参数');
        $goods_name = $this->requestData['keyword'];

        $where['g.name'] = array('like',"%$goods_name%");
        $where['g.status'] = '1';
        $list=db('goods')->alias("g")
            ->field("g.id,g.name,g.image,g.des,min(p.price) as price,min(p.oldprice) as oldprice")
            ->join("goods_option_value p","p.goodsid=g.id")
            ->where($where)
            ->group("g.id")
            ->select();

        //热搜
        $hot_search_goods = Cache::get("hot_search_goods");
        $hot_search_goods = json_decode($hot_search_goods);
        $hot_search_goods[] = $goods_name;

        Cache::set("hot_search_goods", json_encode($hot_search_goods), 864000);
        //热搜

        return $list;
    }

    /**
     * 热搜
     */
    public function hot_search(){
        $hot_new_array = array();

        //热搜
        $hot_search_goods = Cache::get("hot_search_goods");
        $hot_search_goods = json_decode($hot_search_goods);

        //将重复的元素值筛选出来
        if(!empty($hot_search_goods)){
            $hot_array = array_count_values($hot_search_goods);

            $i=0;
            foreach($hot_array as $key=>$value){
                $hot_new_array[$i]['search_name'] = $key;
                $hot_new_array[$i]['search_count'] = $value;
                $i++;
            }

            array_multisort(array_column($hot_new_array,'search_count'),SORT_DESC,$hot_new_array);
     
            $hot_new_array = array_slice($hot_new_array,0,4);
        }

        return $hot_new_array;
    }


    /**
     * 商品详情
     */
    public function detail(){
        $goods = db('goods');
        $db_comment = db('comment_product');
        $where['id']=$this->requestData['id'];
        $where['status']=1;
        $list=$goods->where($where)->find();
        if(!$list) return array('message'=>'商品不存在');
        $list['content'] = 'http://'.$_SERVER['HTTP_HOST'].'/Index/index/goods_knowledge_info?type=goods_info&id='.$list['id'];
        if($list['image']) {
            $list['image']=IMG_PATH . $list['image'];
        }
        if(!empty($list['images'])) {
            $list['images'] = unserialize($list['images']);
            foreach ($list['images'] as $k => $v) {
                $list['images'][$k] = IMG_PATH . $v;
            }
        }else{
            $list['images'] = array();
        }

        if(!empty($list['option'])){
            $option = unserialize($list['option']);
            foreach($option as $key=>$value){
                $option_array[] = $value['key'].':'.$value['value'];
            }
            $list['option']=$option_array;
        }else{
            $list['option']=array();
        }   

        //检测商品是否已收藏
        $goods_result = db('collect_goods')->where(array('uid'=>$this->user['userId'],'goodsid'=>$where['id']))->find();

        if(!empty($goods_result))
        {
            //已收藏
            $list['collect_goods'] = 1;
        }else{
            //未收藏
            $list['collect_goods'] = 0;
        }   

        //查询商品价格最高价与最低价
        $goods_option_value_result = db('goods_option_value')->where(array('goodsid'=>$where['id']))->group('goodsid')->field('max(price) as price_max,min(price) as price_min')->find();

        $list['price_max'] = $goods_option_value_result['price_max'];
        $list['price_min'] = $goods_option_value_result['price_min'];

        //评价数
        $db_comment_count = $db_comment->where(array('product_id'=>$where['id']))->count();
        $list['comment_num'] = $db_comment_count;

        //商品规格
        $spec = db("goods_option_category");
        $item = db("goods_option");
        $spec = $spec->field("id,title")->where(array('goodsid'=>$where['id']))->order("id asc")->select();
        foreach ($spec as &$v) {
            $v['list'] = $item->field("title,id")->where("option_category=".$v['id'])->select();
        }
        $list['spec'] = $spec;

        $comment=$db_comment->alias("c")
            ->field("m.headimage,m.id,m.nickname,c.*")
            ->join("member m","m.id=c.memid")
            ->where("c.product_id=". $where['id'])
            ->order("c.createtime desc")->find();

        if(!empty($comment)){
            if($comment['images']){
                $images = unserialize($comment['images']);
                foreach($images as &$d){
                    $d=IMG_PATH.$d;
                }
                $comment['images']=$images;
            }else{
                $comment['images']=array();
            }
            $comment['headimage'] = get_headimage($comment['headimage'],$comment['memid']);
        }else{
            $comment = null;
        }

        return array("detail"=>$list,"comment"=>$comment);
    }

    /*
  * 规格列表
  */
    public function spec()
    {
        $id = intval($this->requestData['goodsid']);
        if (!$id) return array('message' => '参数有误');
        $where['goodsid'] = $id;
        $spec = db("goods_option_category");
        $item = db("goods_option");
        $spec = $spec->field("id,title")->where($where)->order("id asc")->select();
        foreach ($spec as &$v) {
            $v['list'] = $item->field("title,id")->where("option_category=".$v['id'])->select();
        }
        return $spec;
    }
    /*
 * 选择规格
 */
    public function option()
    {
        $id = intval($this->requestData['goodsid']);
        if (!$id) return array('message' => '参数有误');
        $ids = $this->requestData['ids'];
        $ids=explode(",",$ids);
        asort($ids);
        $where['goodsid'] = $id;
        $where['specs'] = implode(",",$ids);
        $option = db("goods_option_value")->where($where)->find();
        if (!$option) array("message" => '记录不存在');
        $option['price'] = floatval($option['price']);
        return $option;
    }

    /**
     * 商品评论
     */
    public function comment(){
        $comment = db('comment_product');
        $p=isset($this->requestData['page'])?$this->requestData['page']:'1';
        $size=isset($this->requestData['limit'])?$this->requestData['limit']:'10';
        $where['c.product_id']=$this->requestData['goodsid'];
       
        //$where['c.status']=0;
        $list=$comment->alias("c")
            ->field("m.headimage,m.id,m.nickname,c.*")
            ->join("member m","m.id=c.memid")
            ->where($where)
            ->page($p,$size)
            ->order("createtime desc")->select();
        $count=$comment->alias("c")
            ->join("member m","m.id=c.memid")
            ->where($where)->count();

        if(!empty($list)){
            foreach($list as &$v){
                if($v['images']){
                    $images=unserialize($v['images']);
                   foreach($images as &$d){
                        $d=IMG_PATH.$d;
                    }
                    $v['images']=$images;
                }else{
                    $v['images']=array();
                }
                $v['createtime']=date("Y-m-d",$v['createtime']);
                //头像
                $v['headimage']=get_headimage($v['headimage'],$v['memid']);
            }
        }else{
            $list = null;
        }
        return array("list"=>$list,'page_num'=>$p,'page_limit'=>$size,'count'=>$count);
    }
}